package com.unicom.si.security.service;

import com.unicom.si.security.dao.AuthorityDAO;
import com.unicom.si.security.dao.UserDAO;
import com.unicom.si.security.pojo.CustomeUserDetail;
import com.unicom.si.security.pojo.MyGrantedAuthority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("customeUserDetailsService")
public class CustomerUserDetailsService implements UserDetailsService{

    @Autowired
    private AuthorityDAO authDAO;

    @Autowired
    private UserDAO userDAO;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CustomeUserDetail user = null;

        List<CustomeUserDetail> userlist = userDAO.queryUserByUserName(username);

        if(userlist != null && userlist.size() == 1) {
            user = userlist.get(0);
            user.setAccountNonExpired(true);
            user.setAccountNonLocked(true);
            user.setCredentialsNonExpired(true);

            List<MyGrantedAuthority> grantedList = authDAO.queryUserAuthority(user.getCompid(), username);

            Set<GrantedAuthority> dbAuthsSet = new HashSet();
            if(grantedList != null && grantedList.size() > 0) {
                dbAuthsSet.addAll(grantedList);
            }
            user.setAuthorities(dbAuthsSet);
        } else {
           throw new UsernameNotFoundException("没有查到用户，或者存在多个用户");
        }

        return user;
    }
}
